/*
 * @ModuleCode:
 * @Author: 张泽涛
 * @Date: 2023-10-24 10:35:08
 * @LastEditors: 张泽涛
 * @LastEditTime: 2023-12-18 15:08:36
 * @Description:
 */
define([
  ELMP.resource('checkListManage/index.js', 'r_apis'),
  ELMP.resource('components/thumbnail-line/index.js', 'workflow_sdk'),
  ELMP.resource('components/member-org-extend-list/index.js', 'xawdz_workflow'),
  ELMP.resource('components/base-info-extend/index.js', 'xawdz_workflow'),
  ELMP.resource('index.js', 'workflow_sdk'),
  ELMP.resource('components/file-list/index.js', 'xawdz_workflow'),
  'EventBus'
], function (comApi, ThumbnailLine, MemberList, BaseInfo, WorkflowSdk, FileList, EventBus) {
  'use strict'
  function calcKey (key) {
    return `__workflow__${key}`
  }
  const api = { fetchProcessInfosByProcessKey: WorkflowSdk.getApi('fetchProcessInfosByProcessKey') }
  const methods = {
    fetchType: calcKey('fetchType'),
    getProcessInfos: calcKey('getProcessInfos'),
    initdata: calcKey('initdata')
  }
  return {
    data () {
      return {
        pboId: '',
        businessKey: '',
        typeOid: '',
        typeName: '',
        processInfo: {
          id: '',
          activities: []
        }
      }
    },
    components: {
      ThumbnailLine,
      MemberList,
      BaseInfo,
      FileList
    },
    async created () {
      WorkflowSdk.useCache().delete('processInfo')
      EventBus.emit('xawdz:processDraft:pboId', (processRow) => {
        this.pboId = processRow.params
      })
      this.typeOid = await this[methods.fetchType]()
      this.processInfo = await this[methods.getProcessInfos](this.businessKey)
      // this[methods.initdata]()
    },
    computed: {
      // 开始节点id
      startEventActivityId () {
        return this.flowLink.head?.data ?? ''
      },
      // 流程链表
      flowLink () {
        const activities = this.processInfo.activities ?? []
        const startNode = activities.find(node => node.properties.type === 'startEvent')
        const endNode = activities.find(node => node.properties.type === 'endEvent')
        const nodeList = activities.filter(node => node.properties.type === 'userTask' && node.properties.serialnumber)
        nodeList.sort((before, after) => parseInt(before.properties.serialnumber) - parseInt(after.properties.serialnumber))
        startNode && nodeList.unshift(startNode)
        endNode && nodeList.push(endNode)
        return $.flow.createFlowMap(nodeList.map(node => node.activityId))
      }
    },
    methods: {
      getdata (data) {
      },
      async getinitdata (id) {
        const res = await WorkflowSdk.getApi('findPboDraftInfo')(this.pboId, id ?? '', this.startEventActivityId)
        if (res?.data) {
          this.pboId = res.data[0].baseForm.processBasicInfo.oid
          this.getdata(res.data[0])
        } else {
          this.getdata()
        }
      },
      async [methods.initdata] (id) {
        const res = await WorkflowSdk.getApi('findPboDraftInfo')(this.pboId, id, this.startEventActivityId)
        if (res?.data) {
          this.pboId = res.data[0].baseForm.processBasicInfo.oid
          this.getdata(res.data[0])
        } else {
          this.getdata()
        }
      },
      saveloading (isDraft) {
        if (isDraft) {
          $.msg.loading('草稿保存中')
        } else {
          $.msg.loading('流程启动中')
        }
      },
      saveDataAfter (isDraft, code) {
        if (code === '200') {
          if (isDraft) {
            $.msg.success('保存草稿成功')
          } else {
            $.msg.success('流程启动成功')
          }
          $.form.closeSidepage()
        } else {
          if (isDraft) {
            $.msg.error('保存草稿失败')
          } else {
            $.msg.error('流程启动失败')
          }
        }
      },
      // 创建启动流程参数
      createStartFormData ({
        isDraft, reviewItemList, pboId, businessKey,
        businessFormJsonStr, baseInfo, customformJson,
        category, roleMap, userMap, uploadFileIds
      }) {
        // 启动流程的参数
        const formData = {
          isDraft,
          pboId,
          processDefKey: businessKey,
          baseForm: {
            businessForm: {
              reviewItemList: reviewItemList.map(c => { return { oid: c.oid } })
            },
            businessFormJsonStr,
            processBasicInfo: {
              name: baseInfo.name,
              description: baseInfo.description,
              procInstVariables: {}
            }
          },
          baseStartProcessDto: {
            title: baseInfo.name,
            customformJson,
            category,
            deleteFileIds: [],
            description: baseInfo.description,
            dueDate: baseInfo.dueDate,
            priority: baseInfo.priority,
            roleMap,
            userMap,
            uploadFileIds
          }
        }
        return formData
      },
      async [methods.fetchType] () {
        const { getTypesApi } = comApi
        const resp = await getTypesApi({
          typeName: this.typeName
        })
        return resp.data[0].typeOid
      },
      // 流程数据信息
      [methods.getProcessInfos] (processDefinitionKey) {
        const dtd = $.Deferred()
        api.fetchProcessInfosByProcessKey(processDefinitionKey).then(resp => {
          if (resp.success) {
            let data = {
              processDefinition: {},
              activities: []
            }
            try {
              data = JSON.parse(resp.res.data)
            } catch (e) {
              console.error(e)
            }
            dtd.resolve({
              id: data.processDefinition.id,
              name: data.processDefinition.name,
              activities: data.activities,
              deploymentId: data.processDefinition.deploymentId,
              users: resp.res.users
            })
          } else {
            dtd.reject(resp)
          }
        }, dtd.reject)
        return dtd
      },
      // 获取数据
      handleCloseClick () {
        $.form.closeSidepage()
      },
      // 流程图解
      viewFlowChart () {
        WorkflowSdk.openFlowChart({
          processDefinitionId: this.processInfo.id
        })
      }
    }
  }
})
